package com.wty.cmims.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wty.cmims.mapper.MedicalHistoryMapper;
import com.wty.cmims.mapper.PrescriptionMapper;
import com.wty.cmims.pojo.Appointment;
import com.wty.cmims.pojo.Code;
import com.wty.cmims.pojo.MedicalHistory;
import com.wty.cmims.pojo.Prescription;
import com.wty.cmims.pojo.ResponseResult;
import com.wty.cmims.pojo.Schedule;
import com.wty.cmims.service.AppointmentService;
import com.wty.cmims.mapper.AppointmentMapper;
import com.wty.cmims.service.ScheduleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
* @author wty
* @description 针对表【appointment】的数据库操作Service实现
* @createDate 2024-11-16 19:25:59
*/
@Service
public class AppointmentServiceImpl extends ServiceImpl<AppointmentMapper, Appointment>
    implements AppointmentService{
    @Autowired
    private AppointmentMapper appointmentMapper;
    @Autowired
    private MedicalHistoryMapper medicalHistoryMapper;
    @Autowired
    private PrescriptionMapper prescriptionMapper;
    @Autowired
    private ScheduleService scheduleService;

    @Override
    public ResponseResult<Map<String, Object>> appointmentsFind(Map<String, Object> paramsMap) {
        // 分页
        ResponseResult<Map<String, Object>> responseResult = new ResponseResult<>();
        Integer pageSize = (Integer) paramsMap.get("pageSize");
        paramsMap.put("start", ((Integer) paramsMap.get("currentPage") - 1) * pageSize);
        responseResult.setPageSize(pageSize);

        List<Map<String, Object>> appointments = new ArrayList<>();
        Integer total = 0;
        Integer role = (Integer) paramsMap.get("role");
        SimpleDateFormat sdfDay = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            if (paramsMap.get("date") != null){
                date = sdfDay.parse(paramsMap.get("date").toString());
            }
        } catch (ParseException e) {
            System.out.println("日期转换错误");
        }
        if (date != null) {
            paramsMap.put("date", sdfDay.format(date));
        }
        if (role == 2){
            appointments = appointmentMapper.findAppointments(paramsMap);
            total = appointmentMapper.findAppointmentsNum(paramsMap);
        } else if(role == 1){
            appointments = appointmentMapper.findAppointmentsDoctor(paramsMap);
            total = appointmentMapper.findAppointmentsDoctorNum(paramsMap);
            // appointments中，如果status==2，将该条移到前面
            int index = 0;
            List<Map<String, Object>> temp = new ArrayList<>();
            Iterator<Map<String, Object>> iterator = appointments.iterator();
            while (iterator.hasNext()) {
                Map<String, Object> map = iterator.next();
                if (map.get("status").equals(2)) {
                    temp.add(index++, map);
                    iterator.remove();
                } else {
                    temp.add(map);
                }
            }
            appointments = temp;
        }
        if (appointments != null) {
            responseResult.setCode(Code.SUCCESS);
            responseResult.setMessage("查询预约列表成功");
            responseResult.setDatas(appointments);
            responseResult.setTotal(total);
            responseResult.setCurrentPage((Integer) paramsMap.get("currentPage"));
        } else {
            responseResult.setCode(Code.ERROR);
            responseResult.setMessage("查询预约列表失败");
        }
        return responseResult;
    }

    @Override
    public ResponseResult<Void> appointmentUpdate(Map<String, Object> paramsMap) {
        ResponseResult<Void> responseResult = new ResponseResult<>();
        Integer status = (Integer) paramsMap.get("status");
        Integer role = (Integer) paramsMap.get("role");
        if (role == 2){
            if (status == 0 || status == 1){
                LambdaUpdateWrapper<Appointment> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(Appointment::getId, paramsMap.get("id"));
//                 updateWrapper.eq(Appointment::getResidentId, paramsMap.get("resident_id"));
//                 updateWrapper.eq(Appointment::getScheduleId, paramsMap.get("schedule_id"));
                if (status == 0){
                    updateWrapper.set(Appointment::getStatus, 1);
                } else {
                    updateWrapper.set(Appointment::getStatus, 4);
                }
                boolean update = this.update(updateWrapper);
                if (update){
                    responseResult.setCode(Code.SUCCESS);
                    if (status == 0){
                        // 使排班表对应排班预约号次减一
                        LambdaUpdateWrapper<Schedule> wrapper = new LambdaUpdateWrapper<>();
                        wrapper.eq(Schedule::getId, paramsMap.get("schedule_id"))
                                .setSql("rest = rest - 1");
                        boolean confirm = scheduleService.update(wrapper);
                        if (confirm) {
                            responseResult.setMessage("已确认预约挂号");
                        }
                    } else {
                        // 使排班表对应排班预约号次加一
                        LambdaUpdateWrapper<Schedule> wrapper2 = new LambdaUpdateWrapper<>();
                        wrapper2.eq(Schedule::getId, paramsMap.get("schedule_id"))
                                .setSql("rest = rest + 1");
                        boolean rollback = scheduleService.update(wrapper2);
                        if (rollback) {
                            responseResult.setMessage("已退回预约挂号");
                        }
                    }
                }
                return responseResult;
            } else {
                responseResult.setCode(Code.ERROR);
                responseResult.setMessage("操作挂号状态时出现异常");
            }
        } else if (role == 1) {
            if (status == 1 || status == 2){
                LambdaUpdateWrapper<Appointment> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(Appointment::getId, paramsMap.get("id"));
//                updateWrapper.eq(Appointment::getResidentId, paramsMap.get("resident_id"));
//                updateWrapper.eq(Appointment::getScheduleId, paramsMap.get("schedule_id"));
                if (status == 1){
                    updateWrapper.set(Appointment::getStatus, 2);
                } else {
                    // 检查是否已生成病历
                    LambdaQueryWrapper<MedicalHistory> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(MedicalHistory::getAppointmentId, paramsMap.get("id"));
                    MedicalHistory medicalHistory = medicalHistoryMapper.selectOne(wrapper);
                    if (medicalHistory == null){
                        responseResult.setCode(Code.ERROR);
                        responseResult.setMessage("请先生成病历和处方");
                        return responseResult;
                    }
                    // 检查是否已生成处方
                    LambdaQueryWrapper<Prescription> wrapper2 = new LambdaQueryWrapper<>();
                    wrapper2.eq(Prescription::getHistoryId, medicalHistory.getId());
                    Prescription prescription = prescriptionMapper.selectOne(wrapper2);
                    if (prescription == null){
                        responseResult.setCode(Code.ERROR);
                        responseResult.setMessage("请先生成处方");
                        return responseResult;
                    }
                    updateWrapper.set(Appointment::getStatus, 3);
                }
                boolean update = this.update(updateWrapper);
                if (update){
                    responseResult.setCode(Code.SUCCESS);
                    if (status == 1){
                        responseResult.setMessage("问诊开始");
                    } else {
                        responseResult.setMessage("问诊结束");
                    }
                }
                return responseResult;
            } else {
                responseResult.setCode(Code.ERROR);
                responseResult.setMessage("操作挂号状态时出现异常");
            }
        }
        return responseResult;
    }
}